{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "d1f20875-c50d-46df-906b-49ec1d0c6002",
   "metadata": {},
   "source": [
    "## 9.8 保存和加载整个模型\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c90a18b9-d8e8-431c-856c-35f1e4ed05e1",
   "metadata": {},
   "source": [
    "### 1.任务描述\n",
    "\n",
    "训练手写数字网络，并保存并加载整个模型。"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "f5b4fc39-cbcf-432a-bf1e-e75e642d4b87",
   "metadata": {},
   "source": [
    "### 2.知识准备\n",
    "\n",
    "见教程。"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "55043130-4496-43a3-803b-9bc1cea8b1b8",
   "metadata": {},
   "source": [
    "### 3.任务分析构\n",
    "\n",
    "在使用model.save保存模型时，模型也可以被存储为HDF5格式或SaveModel格式。\n",
    "\n",
    "如果给定了后缀为.h5，建议设置save_format=None，此时，模型被保存为.h5文件。\n",
    "\n",
    "如果没有给定后缀名，Keras就会认为这是一个目录，把它保存为SavedModel格式。为了程序更加清楚，建议设置save_format=tf。\n",
    "\n",
    "保存了完整的模型后，在下载使用时可以使用model.load_model方法加载整个模型，无须创建、配置和训练神经网络。\r\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "435c6090-cfda-4f46-a550-22a368e41e4a",
   "metadata": {},
   "source": [
    "### 4.任务实施\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ec75eb6c-5da3-467d-a471-ca3b47242dd6",
   "metadata": {},
   "source": [
    "执行代码"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "2ae9da58-e339-4d22-9f8d-ca255711d89e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Epoch 1/5\n",
      "235/235 [==============================] - 1s 3ms/step - loss: 0.4456 - sparse_categorical_accuracy: 0.8799 - val_loss: 0.2280 - val_sparse_categorical_accuracy: 0.9342\n",
      "Epoch 2/5\n",
      "235/235 [==============================] - 1s 2ms/step - loss: 0.1992 - sparse_categorical_accuracy: 0.9441 - val_loss: 0.1625 - val_sparse_categorical_accuracy: 0.9532\n",
      "Epoch 3/5\n",
      "235/235 [==============================] - 1s 2ms/step - loss: 0.1478 - sparse_categorical_accuracy: 0.9578 - val_loss: 0.1377 - val_sparse_categorical_accuracy: 0.9597\n",
      "Epoch 4/5\n",
      "235/235 [==============================] - 1s 2ms/step - loss: 0.1165 - sparse_categorical_accuracy: 0.9674 - val_loss: 0.1127 - val_sparse_categorical_accuracy: 0.9663\n",
      "Epoch 5/5\n",
      "235/235 [==============================] - 1s 2ms/step - loss: 0.0965 - sparse_categorical_accuracy: 0.9729 - val_loss: 0.0993 - val_sparse_categorical_accuracy: 0.9709\n",
      "Model: \"sequential\"\n",
      "_________________________________________________________________\n",
      " Layer (type)                Output Shape              Param #   \n",
      "=================================================================\n",
      " flatten (Flatten)           (None, 784)               0         \n",
      "                                                                 \n",
      " dense (Dense)               (None, 128)               100480    \n",
      "                                                                 \n",
      " dense_1 (Dense)             (None, 10)                1290      \n",
      "                                                                 \n",
      "=================================================================\n",
      "Total params: 101,770\n",
      "Trainable params: 101,770\n",
      "Non-trainable params: 0\n",
      "_________________________________________________________________\n",
      "1/1 [==============================] - 0s 54ms/step\n",
      "预测值： 1\n"
     ]
    },
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAaAAAAGdCAYAAABU0qcqAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMywgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy/NK7nSAAAACXBIWXMAAA9hAAAPYQGoP6dpAAAac0lEQVR4nO3dfWxU973n8c8A9gQSe6gx9niCoYYQSENwbym4viSUFC/G0UU83Yo8dBeiCAQx2QJNk3WVhKSt5IZIaZTUBe1uC41uIA9SgA1KqYiJjdLadHFgEdvUF1tuMYttGrSeMSYYg3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y6KPV4dUAAAAAElFTkSuQmCC",
      "text/plain": [
       "<Figure size 640x480 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "from matplotlib import pyplot as plt\n",
    "import numpy as np\n",
    "# 加载数据\n",
    "mnist = tf.keras.datasets.mnist\n",
    "(x_train, y_train), (x_test, y_test) = mnist.load_data()\n",
    "x_train, x_test = x_train / 255.0, x_test / 255.0\n",
    "\n",
    "# 创建网络\n",
    "model1=tf.keras.Sequential()\n",
    "model1.add(tf.keras.layers.Flatten(input_shape=(28,28)))\n",
    "model1.add(tf.keras.layers.Dense(128,activation=\"relu\"))\n",
    "model1.add(tf.keras.layers.Dense(10,activation=\"softmax\"))\n",
    "\n",
    "# 配置网络\n",
    "model1.compile(optimizer='adam',\n",
    "              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),\n",
    "              metrics=['sparse_categorical_accuracy'])\n",
    "\n",
    "# 执行训练\n",
    "model1.fit(x_train, y_train, batch_size=256, epochs=5, validation_data=(x_test, y_test), \n",
    "          validation_freq=1)\n",
    "\n",
    "# 打印网络结构\n",
    "model1.summary()\n",
    "\n",
    "# 保存为HDF5格式\n",
    "model1.save(filepath=\"mnist_model.h5\",overwrite=True,save_format=None)\n",
    "\n",
    "# 加载模型\n",
    "model2 = tf.keras.models.load_model(\"mnist_model.h5\")\n",
    "# 使用模型\n",
    "img=x_test[5]\n",
    "plt.imshow(img)\n",
    "img=tf.reshape(img,(1,28,28))\n",
    "result=model2.predict(img)\n",
    "num=np.argmax(result)\n",
    "print(\"预测值：\",num)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e6044c99-0741-4378-b2b6-f60c293cc3a9",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
